package com.jfirer.validator.validation;

import com.jfirer.baseutil.reflect.ReflectUtil;

import java.util.Map.Entry;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorFactory;

public class DefaultConstraintValidatorFactory implements ConstraintValidatorFactory
{
	private ConcurrentMap<Class<?>, ConstraintValidator<?, ?>> store = new ConcurrentHashMap<Class<?>, ConstraintValidator<?, ?>>();
	
	@SuppressWarnings("unchecked")
	@Override
	public <T extends ConstraintValidator<?, ?>> T getInstance(Class<T> key)
	{
		T constraintValidator = (T) store.get(key);
		if (constraintValidator == null)
		{
			try
			{
				constraintValidator = key.newInstance();
				store.putIfAbsent(key, constraintValidator);
				constraintValidator = (T) store.get(key);
			}
			catch (Exception e)
			{
				ReflectUtil.throwException(e);
			}
		}
		return constraintValidator;
	}
	
	@Override
	public void releaseInstance(ConstraintValidator<?, ?> instance)
	{
		Object removeKey = null;
		for (Entry<Class<?>, ConstraintValidator<?, ?>> entry : store.entrySet())
		{
			if (entry.getValue() == instance)
			{
				removeKey = entry.getKey();
				break;
			}
		}
		store.remove(removeKey);
	}
	
}
